package com.ming.gateway.controller;

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ming.gateway.config.SwaggerResourceConfig;
import com.ming.gateway.model.UrlConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.SwaggerResource;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @Classname HealthyController
 * @Description 健康检查类
 * @Date 2021/1/12 11:31
 * @Created by yanming.fu
 */
@RestController
@Slf4j
@RefreshScope
public class HealthyController {

    @Autowired
    SwaggerResourceConfig swaggerResourceConfig;
    @Autowired
    private UrlConfig urlConfig ;
    @Value("${ming.info}")
    private String envInfo;

    /**
     * @Description 主请求
     * @return java.lang.String
     * @date 2021/2/1 9:31
     * @auther yanming.fu
     */
    @GetMapping("/")
    public String index(){
        log.error("网关放行的Url地址为:[{}]", JSON.toJSONString(urlConfig.getNorequire().getUrls()));
        return "网关服务正在运行...";
    }


    /**
     * @Description 获取聚合Swagger内容
     * @return java.lang.String
     * @date 2021/2/1 9:30
     * @auther yanming.fu
     */
    @GetMapping("/gw/swagger")
    public String check(){
        List<SwaggerResource> swaggerResources = swaggerResourceConfig.get();
        return JSONArray.toJSONString(swaggerResources);
    }


    /**
     * @Description 获取当前系统得限流策略
     * @return java.util.Set<com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule>
     * @date 2021/2/1 9:27
     * @auther yanming.fu
     */
    @GetMapping("/gw/flow/rules")
    public Set<GatewayFlowRule> getCurrentGatewayFlowRules(){
        return GatewayRuleManager.getRules();
    }



    /**
     * @Description 获取我定义的API分组
     * @return java.util.Set<com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition>
     * @date 2021/2/1 9:29
     * @auther yanming.fu
     */
    @GetMapping("/gw/api/groups")
    public Set<ApiDefinition> getApiGroups(){
        return GatewayApiDefinitionManager.getApiDefinitions();
    }

}
